package com.czh.www.main;

import com.czh.www.domain.DataPacket;
import com.czh.www.domain.SystemVar;
import com.czh.www.domain.UsersVo;
import com.czh.www.gui.IUserListGui;
import com.czh.www.thread.DataPacketHandler;
import com.czh.www.thread.RecvPacketDaemon;
import com.czh.www.util.GuiUtils;
import com.czh.www.util.IpMsgUtils;
import com.czh.www.util.NetUtils;

import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.SoftBevelBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class Start extends JFrame implements IUserListGui {
    private JButton jButton1;
    private JButton jButton2;
    private JLabel jLabel1;
    private JPanel jPanel1;
    private JPanel jPanel2;
    private JPanel jPanel3;
    private JPanel jPanel4;
    private JPanel jPanel5;
    private JScrollPane jScrollPane1;
    private JScrollPane jScrollPane2;
    private JScrollPane jScrollPane3;
    private JSplitPane jSplitPane1;
    private JTable jTable1;
    private JTextArea jTextArea1;
    private JTextArea jTextArea2;
    private Label label1;

    public Start() {
        this.preCheck();
        this.initComponents();
        SystemVar.init();
        SystemVar.setUserListGui(this);
        (new Thread(new RecvPacketDaemon())).start();
        (new Thread(new DataPacketHandler())).start();
        this.login();
    }

    private void login() {
        DataPacket dp = new DataPacket(1);
        dp.setAdditional(SystemVar.USER_NAME + '\u0000' + "");
        dp.setIp(NetUtils.getLocalHostIp());
        UsersVo user = UsersVo.changeDataPacket(dp);
        SystemVar.addUsers(user);
        this.addUserVo(user);
        this.updateUserNum(1);
        NetUtils.broadcastUdpPacket(dp);
    }

    private void preCheck() {
        if (!NetUtils.checkPort()) {
            GuiUtils.showNotice(this, "端口已经被占用！");
            System.exit(0);
        }

    }

    private void initComponents() {
        this.jSplitPane1 = new JSplitPane();
        this.jScrollPane1 = new JScrollPane();
        this.jTextArea1 = new JTextArea();
        this.jPanel1 = new JPanel();
        this.jScrollPane3 = new JScrollPane(this.jTable1);
        this.jTable1 = new JTable();
        this.jPanel4 = new JPanel();
        this.jButton2 = new JButton();
        this.jPanel5 = new JPanel();
        this.jLabel1 = new JLabel();
        this.label1 = new Label();
        this.jPanel2 = new JPanel();
        this.jScrollPane2 = new JScrollPane();
        this.jTextArea2 = new JTextArea();
        this.jPanel3 = new JPanel();
        this.jButton1 = new JButton();
        this.setDefaultCloseOperation(3);
        this.setTitle("JIPMsg");
        this.setBounds(new Rectangle(200, 200, 0, 0));
        this.setCursor(new Cursor(0));
        this.setIconImage(Toolkit.getDefaultToolkit().createImage(Start.class.getResource("") + "resources/ipmsg.JPG"));
        this.jSplitPane1.setDividerLocation(240);
        this.jSplitPane1.setOrientation(0);
        this.jSplitPane1.setToolTipText("");
        this.jSplitPane1.setName("");
        this.jTextArea1.setColumns(20);
        this.jTextArea1.setRows(5);
        this.jScrollPane1.setViewportView(this.jTextArea1);
        this.jSplitPane1.setBottomComponent(this.jScrollPane1);
        this.jPanel1.setLayout(new BorderLayout());
        this.jScrollPane3.setViewportBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
        this.jScrollPane3.setAutoscrolls(true);
        this.jTable1.setModel(new DefaultTableModel(new Object[0][], new String[]{"用户名", "工作组", "主机名", "IP地址"}) {
            Class[] types = new Class[]{String.class, String.class, String.class, String.class};
            boolean[] canEdit = new boolean[]{false, false, false, false};

            public Class getColumnClass(int columnIndex) {
                return this.types[columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return this.canEdit[columnIndex];
            }
        });
        this.jTable1.setAutoResizeMode(4);
        this.jTable1.setPreferredSize(new Dimension(300, 230));
        this.jTable1.setRequestFocusEnabled(false);
        this.jScrollPane3.setViewportView(this.jTable1);
        this.jPanel1.add(this.jScrollPane3, "Center");
        this.jPanel4.setPreferredSize(new Dimension(80, 239));
        this.jButton2.setText("刷新");
        this.jButton2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                Start.this.jButton2ActionPerformed(evt);
            }
        });
        this.jPanel5.setBorder(new SoftBevelBorder(1));
        this.jLabel1.setFont(new Font("Dialog", 0, 12));
        this.jLabel1.setHorizontalAlignment(0);
        this.jLabel1.setText("在线人数");
        this.jLabel1.setVerticalAlignment(1);
        this.jLabel1.setMaximumSize(new Dimension(48, 15));
        this.jLabel1.setMinimumSize(new Dimension(48, 15));
        this.jLabel1.setPreferredSize(new Dimension(48, 15));
        GroupLayout jPanel5Layout = new GroupLayout(this.jPanel5);
        this.jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(jPanel5Layout.createParallelGroup(Alignment.LEADING).addComponent(this.jLabel1, -1, 59, 32767).addGroup(jPanel5Layout.createSequentialGroup().addGap(20, 20, 20).addComponent(this.label1, -2, 16, -2).addContainerGap(23, 32767)));
        jPanel5Layout.setVerticalGroup(jPanel5Layout.createParallelGroup(Alignment.LEADING).addGroup(jPanel5Layout.createSequentialGroup().addComponent(this.jLabel1, -2, 15, -2).addPreferredGap(ComponentPlacement.RELATED).addComponent(this.label1, -1, -1, 32767).addContainerGap()));
        GroupLayout jPanel4Layout = new GroupLayout(this.jPanel4);
        this.jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(jPanel4Layout.createParallelGroup(Alignment.LEADING).addGroup(jPanel4Layout.createSequentialGroup().addContainerGap().addComponent(this.jButton2, -1, -1, 32767).addGap(12, 12, 12)).addGroup(jPanel4Layout.createSequentialGroup().addGap(6, 6, 6).addComponent(this.jPanel5, -1, -1, 32767).addContainerGap()));
        jPanel4Layout.setVerticalGroup(jPanel4Layout.createParallelGroup(Alignment.LEADING).addGroup(jPanel4Layout.createSequentialGroup().addGap(24, 24, 24).addComponent(this.jPanel5, -2, 50, -2).addGap(53, 53, 53).addComponent(this.jButton2).addContainerGap(87, 32767)));
        this.jPanel1.add(this.jPanel4, "After");
        this.jSplitPane1.setLeftComponent(this.jPanel1);
        this.jPanel2.setLayout(new BorderLayout());
        this.jTextArea2.setColumns(20);
        this.jTextArea2.setRows(5);
        this.jScrollPane2.setViewportView(this.jTextArea2);
        this.jPanel2.add(this.jScrollPane2, "Center");
        this.jPanel3.setPreferredSize(new Dimension(468, 50));
        this.jButton1.setText("发送");
        this.jButton1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                Start.this.jButton1ActionPerformed(evt);
            }
        });
        this.jPanel3.add(this.jButton1);
        this.jPanel2.add(this.jPanel3, "Last");
        this.jSplitPane1.setRightComponent(this.jPanel2);
        GroupLayout layout = new GroupLayout(this.getContentPane());
        this.getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(Alignment.LEADING).addComponent(this.jSplitPane1, -1, 470, 32767));
        layout.setVerticalGroup(layout.createParallelGroup(Alignment.LEADING).addComponent(this.jSplitPane1, Alignment.TRAILING, -1, 424, 32767));
        this.pack();
    }

    private void jButton2ActionPerformed(ActionEvent evt) {
        SystemVar.clearUsers();
        this.clearTable();
        this.login();
    }

    private void jButton1ActionPerformed(ActionEvent evt) {
        int[] rowIndex = this.jTable1.getSelectedRows();
        if (rowIndex.length == 0) {
            GuiUtils.showNotice(this, "请选择发送用户！");
        } else {
            for (int i = 0; i < rowIndex.length; ++i) {
                IpMsgUtils.sendMessage(this.jTextArea2.getText(), new String[]{((UsersVo) SystemVar.getUserList().get(rowIndex[i])).getIp()});
            }
        }

        this.jTextArea2.setText("");
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                (new Start()).setVisible(true);
            }
        });
    }

    public void updateUserNum(int num) {
        this.label1.setText(Integer.toString(num));
    }

    public void updateUserList(List<UsersVo> userList) {
        int rowCount = this.jTable1.getRowCount();
        DefaultTableModel model = (DefaultTableModel) this.jTable1.getModel();

        for (int i = 0; i < userList.size(); ++i) {
            UsersVo user = userList.get(i);
            if (i >= rowCount) {
                model.addRow(user.toArray());
            } else {
                model.setValueAt(user.getAlias(), i, 0);
                model.setValueAt(user.getGroupName(), i, 1);
                model.setValueAt(user.getHostName(), i, 2);
                model.setValueAt(user.getIp(), i, 3);
            }
        }

    }

    private void clearTable() {
        int rowCount = this.jTable1.getRowCount();
        DefaultTableModel model = (DefaultTableModel) this.jTable1.getModel();

        for (int i = 0; i < rowCount; ++i) {
            model.removeRow(0);
        }

    }

    public void addUserVo(UsersVo user) {
        DefaultTableModel model = (DefaultTableModel) this.jTable1.getModel();
        model.addRow(user.toArray());
        double tableHeight = this.jTable1.getPreferredSize().getHeight();
        Dimension dTmp = new Dimension((new Double(this.jTable1.getPreferredSize().getWidth())).intValue(), (new Double(tableHeight + tableHeight)).intValue());
        this.jTable1.setPreferredSize(dTmp);
    }

    public void rebackMsg(int rowIdex, String content) {
        this.jTextArea2.setText(content);
        this.jTable1.setRowSelectionInterval(rowIdex, rowIdex);
    }
}
